#include "SiemensMC45.h"
#include "GSMCommandResponse.h"
#include <stdio.h>
#include <system.h>

SiemensMC45::SiemensMC45(DataInput* input, DataOutput* output) :
	GSMCommandResponse(input, output) {}

bool parseExtendedCellData(char* text, ExtendedCellData& result) {
	// skip to next line 2 times, that is 4 linefeeds.
	uint8_t numNewlines = 0;
	uint16_t index = 0;

	result.isValid = false;

	while(numNewlines<4) {
		if(text[index]==13 || text[index]==10) numNewlines++;
		if(text[index]==0) return false;
		index++;
	}

/* example line
  77  30  -80 228  02 7530 283D   1   3  33  -105  25 I    No connection
 */
	int data;
	sscanf(text+index+5,  "%d", &data);
	result.RSSI = data;

	sscanf(text+index+9, "%d", &data);
	result.dBm = data;

	sscanf(text+index+13, "%d", &data);
	result.MCC = data;

	sscanf(text+index+17, "%d", &data);
	result.MNC = data;

	sscanf(text+index+22, "%x", &data);
	result.LAC = data;

	sscanf(text+index+27, "%x", &data);
	result.cellId = data;

	sscanf(text+index+36, "%d", &data);
	result.BCC = data;

	sscanf(text+index+40, "%d", &data);
	result.pwr = data;

	result.isValid = true;

	return true;
}

// This relies on fancy Siemens hacker friendly stuff.
// For those without Siemens phone, try AT+CREG=2 and AT+CREG?, you will get CellID, LAC and nothing more.
bool SiemensMC45::getExtendedCellData(ExtendedCellData& result) {
	uint32_t timeout = getSystemTimeMillis() + 1000UL;
	if (executeCommand((char*)"AT^MONI", tempResponse, timeout)) return false; // The cell monitoring command, very hacky.
	return parseExtendedCellData(tempResponse, result);
}
